package com.yuxl.ai.spg.service;

import com.yuxl.ai.spg.entity.AiSpgEntity;
import com.yuxl.ai.spg.repository.AiSpgEntityRepository;
import com.yuxl.common.auth.utils.JwtUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;

@Slf4j
@Service
public class AiSpgEntityService {
    @Resource
    private AiSpgEntityRepository aiSpgEntityRepository;
    @Resource
    private JwtUtil jwtUtil;

    public Flux<AiSpgEntity> findAll() {
        return aiSpgEntityRepository.findAll();
    }

    public Mono<AiSpgEntity> findById(Long id) {
        return aiSpgEntityRepository.findById(id)
                .defaultIfEmpty(new AiSpgEntity());
    }

    public Mono<Void> deleteById(Long id) {
        return aiSpgEntityRepository.deleteById(id);
    }

    public Mono<AiSpgEntity> create(AiSpgEntity entity) {
        return jwtUtil.getCurrentUser()
                .flatMap(user ->{
                    entity.setCreateBy(user.id());
                    entity.setUpdateBy(user.id());
                    entity.setCreateTime(LocalDateTime.now());
                    entity.setUpdateTime(LocalDateTime.now());
                    return aiSpgEntityRepository.save(entity);
                });
    }

    public Mono<Integer> count(AiSpgEntity entity) {
        return aiSpgEntityRepository.count(entity);
    }


    public Flux<AiSpgEntity> page(AiSpgEntity entity, int page, int size) {
        long offset = (long) (page - 1) * size;
        return aiSpgEntityRepository.page(entity, size, offset);
    }


    public Flux<AiSpgEntity> list(AiSpgEntity entity) {
        return aiSpgEntityRepository.list(entity);
    }

    public Mono<AiSpgEntity> updateById(AiSpgEntity entity) {
        return jwtUtil.getCurrentUser()
                .flatMap(user ->{
                    entity.setUpdateBy(user.id());
                    entity.setUpdateTime(LocalDateTime.now());
                    return aiSpgEntityRepository.updateById(entity)
                            .flatMap(rows -> rows > 0 ? aiSpgEntityRepository.findById(entity.getId()) : Mono.empty());
                });
    }
}
